<?php

namespace App\Console\Commands\OpenShop;

use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderLogModel;
use App\Support\ChangeSupport;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

class RebuildOrderLogCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'OpenShop:RebuildOrderLogCommand';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '开店 - 重构订单日志历史数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        OpenShopSignOrderLogModel::query()
//                                 ->where("type", OpenShopSignOrderLogModel::TYPE_ORDER_CREATED)
                                 ->chunkById(500, function (Collection $orderLogs) {
                                     $orderLogs->each(function (OpenShopSignOrderLogModel $orderLog) {
                                         if ($orderLog->changes && !Str::contains($orderLog->changes, "theme")) {
                                             $this->getOutput()->info($orderLog->id);
                                             switch ($orderLog->type) {
                                                 case OpenShopSignOrderLogModel::TYPE_ORDER_CREATED:
                                                 case OpenShopSignOrderLogModel::SEND_ORDER_CONTRACT_CREATED:
                                                     $orderLog->changes = json_encode($this->buildType_1($orderLog->changes),
                                                         JSON_UNESCAPED_UNICODE);
                                                     $orderLog->save();
                                                     break;
                                                 case OpenShopSignOrderLogModel::TYPE_ORDER_EDITED:
                                                     $orderLog->changes = json_encode($this->buildType_2($orderLog->changes),
                                                         JSON_UNESCAPED_UNICODE);
                                                     $orderLog->save();
                                                     break;
                                                 case OpenShopSignOrderLogModel::TYPE_SIGN_SMS_SENT:
                                                     ChangeSupport::getInstance()->buildInsertChanges("✉️支付短信已发送");
                                                     $orderLog->changes = ChangeSupport::getInstance()
                                                                                       ->getChangeContent();
                                                     $orderLog->save();
                                                     break;
                                                 case OpenShopSignOrderLogModel::SEND_JOIN_SMS:
                                                     ChangeSupport::getInstance()->buildInsertChanges("✉️加盟成功短信已发送");
                                                     $orderLog->changes = ChangeSupport::getInstance()
                                                                                       ->getChangeContent();
                                                     $orderLog->save();
                                                     break;
                                                 case OpenShopSignOrderLogModel::SELECTION_SUBMIT_DISCLOSURE:
                                                     if ($changeContent = json_decode($orderLog->changes, true)) {
                                                         ChangeSupport::getInstance()->buildInsertChanges(
                                                             "上传披露信息",
                                                             [
                                                                 "url" => $changeContent["new"] ?? []
                                                             ],
                                                             [
                                                                 "url" => [
                                                                     "type" => ChangeSupport::FILED_TYPE_PRIVATE_PICTURE,
                                                                     "desc" => "披露单文件地址"
                                                                 ]
                                                             ]
                                                         );

                                                         $orderLog->changes = ChangeSupport::getInstance()
                                                                                           ->getChangeContent();
                                                         $orderLog->save();
                                                     }
                                                     break;
                                                 case OpenShopSignOrderLogModel::UPDATED_SUBMIT_DISCLOSURE:
                                                     if ($changeContent = json_decode($orderLog->changes, true)) {
                                                         $newChanges        = [
                                                             [
                                                                 "theme"      => "修改披露单信息",
                                                                 "changeType" => ChangeSupport::CHANGE_TYPE_SINGLE_UPDATE,
                                                                 "data"       => [
                                                                     [
                                                                         "key"         => "url",
                                                                         "beforeValue" => $changeContent["old"] ?? [],
                                                                         "afterValue"  => $changeContent["new"] ?? [],
                                                                         "beforeText"  => $changeContent["old"] ?? [],
                                                                         "afterText"   => $changeContent["new"] ?? [],
                                                                         "type"        => ChangeSupport::FILED_TYPE_PRIVATE_PICTURE,
                                                                         "description" => "披露单文件地址"
                                                                     ]
                                                                 ]
                                                             ]
                                                         ];
                                                         $orderLog->changes = json_encode($newChanges,
                                                             JSON_UNESCAPED_UNICODE);
                                                         $orderLog->save();
                                                     }
                                                     break;
                                                 case OpenShopSignOrderLogModel::UPLOAD_ORDER_PAY_PROOF:
                                                     if ($changeContent = json_decode($orderLog->changes, true)) {
                                                         ChangeSupport::getInstance()->buildInsertChanges(
                                                             "上传支付凭证",
                                                             [
                                                                 "url"   => $changeContent["proofImg"] ?? [],
                                                                 "price" => $changeContent["price"] ?? 0,
                                                             ],
                                                             [
                                                                 "url"   => [
                                                                     "type" => ChangeSupport::FILED_TYPE_PRIVATE_PICTURE,
                                                                     "desc" => "支付凭证图片"
                                                                 ],
                                                                 "price" => "支付金额"
                                                             ]
                                                         );

                                                         $orderLog->changes = ChangeSupport::getInstance()
                                                                                           ->getChangeContent();
                                                         $orderLog->save();
                                                     }
                                                     break;
                                             }
                                         }
                                     });
                                 });

        return 0;
    }

    public function buildType_2(string $originalChanges)
    {
        $newChanges   = [];
        $singleChange = [
            "theme"      => "",
            "changeType" => ChangeSupport::CHANGE_TYPE_SINGLE_UPDATE,
            "data"       => []
        ];
        $changes      = explode(PHP_EOL, $originalChanges);

        $first = true;
        foreach ($changes as $change) {
            if (empty($change)) {
                $first = true;
                if ($singleChange["data"]) {
                    array_push($newChanges, $singleChange);
                }
                $singleChange = [
                    "theme"      => "",
                    "changeType" => ChangeSupport::CHANGE_TYPE_SINGLE_UPDATE,
                    "data"       => []
                ];
            } else {
                if ($first) {
                    $singleChange["theme"] = $change;
                    $first                 = false;
                } else {
                    $changeField  = explode(strstr($change, ":") ? ":" : "：", $change);
                    $changeDetail = explode("=>", $changeField[1]);
                    array_push($singleChange["data"], [
                        "key"         => "",
                        "beforeValue" => "",
                        "afterValue"  => "",
                        "beforeText"  => $changeDetail[0] ?? "",
                        "afterText"   => $changeDetail[1] ?? "",
                        "type"        => ChangeSupport::FILED_TYPE_STRING,
                        "description" => $changeField[0]
                    ]);
                }
            }
        }

        array_push($newChanges, $singleChange);
        return $newChanges;
    }

    public function buildType_1(string $originalChanges)
    {
        $newChanges   = [];
        $singleChange = [
            "theme"      => "",
            "changeType" => ChangeSupport::CHANGE_TYPE_SINGLE_INSERT,
            "data"       => []
        ];
        $changes      = explode(PHP_EOL, $originalChanges);

        $first = true;
        foreach ($changes as $k => $change) {
            if (empty($change)) {
                $first = true;
                if ($singleChange["data"]) {
                    array_push($newChanges, $singleChange);
                }
                $singleChange = [
                    "theme"      => "",
                    "changeType" => ChangeSupport::CHANGE_TYPE_SINGLE_INSERT,
                    "data"       => []
                ];
            } else {
                if ($first) {
                    $singleChange["theme"] = $change;
                    $first                 = false;
                } else {
                    $changeField = explode(strstr($change, ":") ? ":" : "：", $change);
                    array_push($singleChange["data"], [
                        "key"         => "",
                        "beforeValue" => "",
                        "afterValue"  => "",
                        "beforeText"  => "",
                        "afterText"   => $changeField[1] ?? "",
                        "type"        => ChangeSupport::FILED_TYPE_STRING,
                        "description" => $changeField[0]
                    ]);
                }
            }
        }

        if (!empty($singleChange["data"])) {
            array_push($newChanges, $singleChange);
        }
        return $newChanges;
    }
}
